<?php
/*
 *	微信通用函数
 */
 	//判断是否微信浏览器(待改善)
	function is_wechat_open(){
		$user_agent = $_SERVER['HTTP_USER_AGENT'];
		if ($user_agent!='Mozilla/4.0') {
			return false;
		} else {
			return true;
			// 获取版本号
			//preg_match('/.*?(MicroMessenger\/([0-9.]+))\s*/', $user_agent, $matches);
			//echo '<br>Version:'.$matches[2];
		}
	}
 
	//输出微信地址
	function news_put_url($action,$get=array()){
	  return 'http://'.$_SERVER['SERVER_NAME'].U($action,$get);
	}
	
	//处理输出的动态链接参数
	function wx_put_url($url,$data){
		$url=str_replace('[siteUrl]','http://'.$_SERVER['SERVER_NAME'],$url);
		$url=str_replace('[token_id]',$data['token'],$url);
		//$url=str_replace('[wechat_id]',$data['wechat'],$url);
		return $url;
	}
	
	//获取微信Openid
	function get_openid($token){
		if(is_local()){
			return 'oT3n0slNdW34zHdyqggxbgJ-9FEw';
		}
		
		$name='wx_openid';
		$openid=session($name);
		if($openid!=''){
			return $openid;
		}else{
			$openid=$_GET['openid'];
			if($openid!=''){
				session($name,$openid,3600);
				return $openid;
			}else{
				jump_oauth($token);
				return false;
			}
		}
	}
	
	//通过openid获取用户信息   (force为true 时强制更新缓存)
	function get_openid_user($openid,$force=false){		
		$data=F('openidUser/'.$openid);
		if($data=='' || $force==true){
			$id=M('client_log')->where(array('openid'=>$openid))->getField('id');
			if($id!=''){
				$data=M('client')->where(array('id'=>$id))->find();
			}else{
				$data='empty';
			}
			F('openidUser/'.$openid,$data);
			if($data=='empty') $data='';
		}
		return $data;
	}
	
	//跳转到Oauth
	function jump_oauth($token,$scope='snsapi_userinfo'){
		$conf=get_wx_conf($token);
		C('URL_MODEL',1);
		$back_url=U(GROUP_NAME.'/'.MODULE_NAME.'/'.ACTION_NAME,get_url_data());
		$redirect_uri=U('Wechat/Index/oauth',array('token'=>$token,'url'=>base64_encode($back_url)),C('TMPL_TEMPLATE_SUFFIX'),'',true);
		$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$conf['appid'].'&redirect_uri='.$redirect_uri.'&response_type=code&scope='.$scope.'&state=1#wechat_redirect';
		redirect($url);
	}
	
	//通过code换取access_token
	function code_to_access($code,$token){
		$conf=get_wx_conf($token);
		$url='https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code='.$code.'&grant_type=authorization_code';
		return wx_put_base($token,$url);
	}
	
	//网页获取微信用户信息（有上限）
	function get_wechat($token,$openid,$local=true){
		//$local=true 兼容本地和服务器测试参数 false时直接抓取云端数据
		if(is_local() && $local==true){
			$data=array(
				'openid'=>'oT3n0slNdW34zHdyqggxbgJ-9FEw',
				'nickname'=>'啵哥',
				'sex'=>1,
				'headimgurl'=>'http://wx.qlogo.cn/mmopen/rXlHUuUD4K7Yty7Fe9ibPDa8nTMmAtqfzseqgB6lxdyRDuYibzduBBOiczHncHREUwX6uJ5KELBhMem1qhT0OFzh6tNLIwdIeD4/0',
			);
			return $data;
		}
				
		$url='https://api.weixin.qq.com/cgi-bin/user/info?openid='.$openid.'&lang=zh_CN&access_token=ACCESS_TOKEN';
		$json=wx_put_base($token,$url);
		if(array_key_exists('errcode',$json)){
			return false;
		}else{
			return $json;	
		}
	}
	
	//网页授权方式获取用户信息（无上限）
	function get_oauth_wechat($token,$openid){
		$data=F('oauth/'.$openid);
		if($data==''){									//没有缓存数据则跳转到授权页面
			jump_oauth($token);
		}else{
			if(time()>$data['expires']){				//过期刷新oauth的access_token参数
				$new_conf=oauth_refresh_token($token,$data['refresh_token']);
				if($new_conf['access_token']!=''){		//刷新并缓存
					$new_conf['unionid']=$data['unionid'];
					F('oauth/'.$openid,$new_conf);
				}else{
					return false;
				}
			}else{										//符合条件则获取用户信息
				//此处的ACCESS_TOKEN与基础的ACCESS_TOKEN不一样
				$url='https://api.weixin.qq.com/sns/userinfo?access_token='.$data['access_token'].'&openid='.$openid.'&lang=zh_CN';
				$data=wx_put_base($token,$url);
				return $data;
			}
		}
	}
	
	//刷新oauth的access_token参数
	function oauth_refresh_token($token,$refresh_token){
		$url='https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token='.$refresh_token;
		return $json=wx_put_base($token,$url);
	}
	
	//缓存网页授权用户配置参数
	function cache_oauth_config($openid,$data){
		$data['expires']=time()+$data['expires_in'];
		F('oauth/'.$openid,$data);
	}
	
	//获取某个公众号的参数
	function get_wx_conf($token){
		$data=F('wxUser/'.$token);
		if($data==''){
			$data=M('weixin_user')->where(array('token'=>$token))->find();
			F('wxUser/'.$token,$data);
		}
		return $data;
	}
	
	
	//判断是否需要加密
	function is_msg_code($token){
		$W=get_wx_conf($token);
		if($W['code']==2){
			$data=array(
				'appid'=>$T['appid'],
				'appsecret'=>$T['appsecret'],
			);
			return $data;
		}else{
			return false;
	  	}
	}
	
	//获取access_token参数
	function get_access_token($token){
	  $T=get_wx_conf($token);
	  $time=time();
	  $conf=array(
		'appid'=>$T['appid'],
		'appsecret'=>$T['appsecret'],
		'aeskey'=>$T['aeskey'],
	  );
	  if($T['access_token']=='' || $time>=$T['access_time']){
		  $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$T['appid']."&secret=".$T['appsecret'];
		  $json=curlGet($url,4);
		  if(isset($json['access_token'])){
			  $data=array(
				  'access_token'=>$json['access_token'],
				  'access_time'=>$time+$json['expires_in'],
			  );
			  M('weixin_user')->where(array('token'=>$token))->save($data);
			  F('wxUser/'.$token,null);													//更新缓存
			  $conf['access_token']=$json['access_token'];
		  }else{
			  return false;
		  }
	  }else{
		  $conf['access_token']=$T['access_token'];
	  }
	  return $conf;
	}
	
	//获取jsapi_ticket参数
	function get_jsapi_ticket($token){
		$T=get_wx_conf($token);
		$time=time();
		$conf=array(
			'appid'=>$T['appid'],
			'appsecret'=>$T['appsecret'],
	 	);
		if($T['jsapi_ticket']=='' || $time>=$T['ticket_time']){
			$conf=get_access_token($token);
			$url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$conf['access_token']."&type=jsapi";
			$json=curlGet($url,4);
			if(isset($json['ticket'])){
				$data=array(
					'jsapi_ticket'=>$json['ticket'],
					'ticket_time'=>$time+$json['expires_in'],
				);
				M('weixin_user')->where(array('token'=>$token))->save($data);
				$conf['jsapi_ticket']=$data['jsapi_ticket'];
				$conf['ticket_time']=$data['ticket_time'];
			}else{
				return false;
			}
		}else{
			$conf['jsapi_ticket']=$T['jsapi_ticket'];
			$conf['ticket_time']=$T['ticket_time'];
		}
		return $conf;
	}
	
	//生成微信JS SDK的签名的配置文件
	function wx_js_signature($token){
		$data=get_jsapi_ticket($token);
		$conf=array(
			'jsapi_ticket'=>$data['jsapi_ticket'],
			'noncestr'=>make_rand(16),
			'timestamp'=>time(),
			'url'=>'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],
		);
		$signature="jsapi_ticket=".$conf['jsapi_ticket']."&noncestr=".$conf['noncestr']."&timestamp=".$conf['timestamp']."&url=".$conf['url'];
		$conf['signature']=sha1($signature);
		$conf['appid']=$data['appid'];
		return $conf;
	}
	
	//输出微信JS配置参数
	function show_wx_js_conf($token){
		$data=wx_js_signature($token);
		$str="
		wx.config({
		  debug: false,
		  appId: '".$data['appid']."',
		  timestamp: ".$data['timestamp'].",
		  nonceStr: '".$data['noncestr']."',
		  signature: '".$data['signature']."',
		  jsApiList: [
			'checkJsApi',
			'onMenuShareTimeline',
			'onMenuShareAppMessage',
			'onMenuShareQQ',
			'onMenuShareWeibo',
			'hideMenuItems',
			'showMenuItems',
			'hideAllNonBaseMenuItem',
			'showAllNonBaseMenuItem',
			'translateVoice',
			'startRecord',
			'stopRecord',
			'onRecordEnd',
			'playVoice',
			'pauseVoice',
			'stopVoice',
			'uploadVoice',
			'downloadVoice',
			'chooseImage',
			'previewImage',
			'uploadImage',
			'downloadImage',
			'getNetworkType',
			'openLocation',
			'getLocation',
			'hideOptionMenu',
			'showOptionMenu',
			'closeWindow',
			'scanQRCode',
			'chooseWXPay',
			'openProductSpecificView',
			'addCard',
			'chooseCard',
			'openCard'
		  ]
	  });";
	  return $str;
	}
	
	
	//加密微信消息
	function wx_msg_encode($token,$appId,$encodingAesKey,$text=''){
		import('wxBizMsgCrypt',CLASS_PATH.'wxcode/');
		$timestamp  = $_GET['timestamp'];
		$nonce = $_GET["nonce"];
		$msg_signature  = $_GET['msg_signature'];
		$pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId);
		$errCode = $pc->encryptMsg($text, $timeStamp, $nonce, $encryptMsg);
		if ($errCode == 0) {
			return $encryptMsg;
		} else {
			//print($errCode . "\n");
			return false;
		}
	}

	//解密微信消息
	function wx_msg_decode($token,$appId,$encodingAesKey,$text=''){
		import('wxBizMsgCrypt',CLASS_PATH.'wxcode/');
		$timestamp  = $_GET['timestamp'];
		$nonce = $_GET["nonce"];
		$msg_signature  = $_GET['msg_signature'];
		$pc = new WXBizMsgCrypt($token,$encodingAesKey,$appId);
    	$decryptMsg = "";  								//解密后的明文
    	$errCode = $pc->DecryptMsg($msg_signature, $timestamp, $nonce, $text, $decryptMsg);
		if ($errCode == 0) {
			return $decryptMsg;
		} else {
			//return ($errCode . "\n");
			return false;
		}
	}
	
	//获取多客服用户列表
	function wx_dkf_lists($token){
		$url="https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=ACCESS_TOKEN";
		return wx_put_base($token,$url);
	}
	
	//添加多客服
	function wx_dkf_add($val,$token){
		$data=array(
			'kf_account'=>$val['kf_account'],
			'nickname'=>$val['nickname'],
			'password'=>md5($val['password']),
		);
		$url="https://api.weixin.qq.com/customservice/kfaccount/add?access_token=ACCESS_TOKEN";
		return wx_put_base($token,$url,'post',$data);
	}
	
	//修改多客服
	function wx_dkf_update($val,$token){
		$data=array(
			'kf_account'=>$val['kf_account'],
			'nickname'=>$val['nickname'],
			'password'=>md5($val['password']),
		);
		$url="https://api.weixin.qq.com/customservice/kfaccount/update?access_token=ACCESS_TOKEN";
		return wx_put_base($token,$url,'post',$data);
	}
	
	//删除多客服用户
	function wx_dkf_delete($token,$kf_account){
		$url="https://api.weixin.qq.com/customservice/kfaccount/del?kf_account=".$kf_account."&access_token=ACCESS_TOKEN";
		return wx_put_base($token,$url);
	}
		
	//客服发送接口
	function wx_dkf_send($token,$openid,$data,$type='text'){
		switch($type){
			case 'text';
				$json=array('touser'=>$openid,'msgtype'=>$type,'text'=>array('content'=>'CONTENT'));
				$json=json_encode($json);
				$json=str_replace('CONTENT',$data,$json);
				break;
			case 'voice':
				$json=array('touser'=>$openid,'msgtype'=>$type,'voice'=>array('media_id'=>'MEDIA_ID'));
				$json=json_encode($json);
				$json=str_replace('MEDIA_ID',$data,$json);
				break;
			case 'image':
				$json=array('touser'=>$openid,'msgtype'=>$type,'image'=>array('media_id'=>'MEDIA_ID'));
				$json=json_encode($json);
				$json=str_replace('MEDIA_ID',$data,$json);
				break;
			default:
				break;
		}
		$url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";
		return wx_put_base($token,$url,'post',$json,2);
	}
	
	//获取粉丝组
	function fans_group_lists($token){
		$url="https://api.weixin.qq.com/cgi-bin/groups/get?access_token=ACCESS_TOKEN";
		return wx_put_base($token,$url);
	}
	
	//查询粉丝所在分组
	function fans_in_group($token,$openid){
		$data=array('openid'=>$openid);
		$url="https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=ACCESS_TOKEN";
		return wx_put_base($token,$url,'post',$data);
	}
	
	//添加粉丝组
	function fans_group_add($val,$token){
		$data=array(
			'group'=>array(
				'name'=>'NAME',
			),
		);
		$data=json_encode($data);
		$data=str_replace('NAME',$val,$data);
		$url="https://api.weixin.qq.com/cgi-bin/groups/create?access_token=ACCESS_TOKEN";
		return wx_put_base($token,$url,'post',$data,2);
	}
	
	//修改粉丝组
	function fans_group_update($val,$token){
		$name=$val['name'];
		$val['name']='NAME';
		$data=array(
			'group'=>$val,
		);
		$data=json_encode($data);
		$data=str_replace('NAME',$name,$data);
		$url="https://api.weixin.qq.com/cgi-bin/groups/update?access_token=ACCESS_TOKEN";
		return wx_put_base($token,$url,'post',$data,2);
	}
	
	
	//删除粉丝组
	function fans_group_delete($id,$token){
		$data=array(
			'group'=>array(
				'id'=>$id,
			),
		);
		$data=json_encode($data);
		$url="https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=ACCESS_TOKEN";
		return wx_put_base($token,$url,'post',$data,2);
	}
	
	//获取粉丝列表
	function wx_fans_lists($token,$next_openid=''){
		if($next_openid!=''){
			$url="https://api.weixin.qq.com/cgi-bin/user/get?next_openid=".$next_openid."&access_token=ACCESS_TOKEN";
		}else{
			$url="https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN";
		}
		return wx_put_base($token,$url);
	}
	
	//设置备注名
	function wx_fans_remark($token,$openid,$remark){
		$data=array('openid'=>$openid,'remark'=>'REMARK');
		$data=json_encode($data);
		$data=str_replace('REMARK',$remark,$data);
		$url='https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=ACCESS_TOKEN';
		return wx_put_base($token,$url,'post',$data,2);
	}
	
	//获取微信消息模板ID
	function wx_msg_tpl_id($token,$tpl_mark){
		//没有高级接口公众直接返回FALSE
		if(!wx_model_aim($token,true)) return false;
		
		$cache=F('tplMsgID/'.$token);
		if(array_key_exists($tpl_mark,$cache)){
			return $cache[$tpl_mark];
		}else{
			$data=array('template_id_short'=>$tpl_mark);
			$url="https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=ACCESS_TOKEN";
			$result=wx_put_base($token,$url,'post',$data);
			if($result['errcode']==0){
				$cache[$tpl_mark]=$result['template_id'];
				F('tplMsgID/'.$token,$cache);
				return $result['template_id'];
			}else{
				return false;
			}
		}
	}
	
	//发送微信模板消息
	function wx_msg_tpl($token,$openid,$tplid,$data,$url,$topcolor='#FF0000'){
		$template_id=wx_msg_tpl_id($token,$tplid);
		if($template_id){
			$json='{"touser":"'.$openid.'","template_id":"'.$template_id.'","url":"'.$url.'","topcolor":"'.$topcolor.'","data":{';
			foreach($data as $k=>$v){
				if(is_array($v)){
					$json.='"'.$k.'":{"value":"'.$v['value'].'","color":"'.$v['color'].'"},';
				}else{
					$json.='"'.$k.'":{"value":"'.$v.'","color":"#173177"},';
				}
			}
			$json=rtrim($json,',');
			$json.='}}';
			$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
			return wx_put_base($token,$url,'post',$json,2);
		}else{
			return false;
		}
	}
	
	//获取微信服务器IP
	function get_wx_ip($token){
		$url="https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=ACCESS_TOKEN";
		return wx_put_base($token,$url);
	}
	
	//微信请求基础函数
	function wx_put_base($token,$url,$mode='get',$data,$code=1){
		$conf=get_access_token($token);
		$url=str_replace('ACCESS_TOKEN',$conf['access_token'],$url);
		$url=str_replace('APPID',$conf['appid'],$url);
		$url=str_replace('APPSECRET',$conf['appsecret'],$url);
		if($mode=='get'){
			$json=curlGet($url,4);
		}else if($mode=='post'){
			if($code==1) $data=json_encode($data);		//把数组格式化成JSON格式
			$json=curlPost($url,$data,4);
		}else{
			return false;
		}
		return $json;
	}
	
	//判断是否有接口权限访问该模块
	function wx_model_aim($token,$return=false){
		if($token){
			$data=get_wx_conf($token);
			if($return){
				return $data['is_true']==1 ? true : false;
			}else{
				return $data['is_true']==1 ? true : $this->error('该模块涉及高级接口，只有认证的公众号才可以操作！');;
			}
		}else{
			$this->error('缺少Token参数!');
		}
	}
	
	//判断是否本地测试端
	function is_local(){
		$host=$_SERVER['HTTP_HOST'];
		if(strstr($host,'127.0.0.')){
			return true;
		}else{
			return false;
		}
	}
?>